import { useState, useEffect } from 'react';

import { useService } from '@flowgram.ai/free-layout-editor';

import { ChatModelType } from '@/typings/chatmodel';

import { Combobox, OptionItem } from '../../ui/combobox';
import { CustomService } from '../../../services/custom-service';

export function LlmModelSelect({
  type,
  uri,
  apiKey,
  chatModel,
  onChange,
}: {
  type?: string;
  uri?: string;
  apiKey?: string;
  chatModel?: string;
  onChange?: (label: string) => void;
}) {
  const customService = useService(CustomService);
  const [modelList, setModelList] = useState<OptionItem[]>([]);
  const [selectedModel, setSelectedModel] = useState<OptionItem>({
    label: chatModel || '未设置',
    value: 0,
  });

  // console.log('LlmModelSelect', chatModel);
  async function loadModelList() {
    if (!uri || uri.trim().length === 0 || !type) {
      return;
    }
    const controller = new AbortController();
    const model: ChatModelType = {
      ID: 0,
      Name: '',
      ModelType: type,
      ModelName: '',
      ApiKey: apiKey,
      ApiUrl: uri,
      MaxContextLength: 0,
      StreamingEnabled: false,
    };
    // console.log('start load model list', model);
    customService
      .getChatModelList(model, controller.signal)
      .then((res) => {
        console.log('getChatModelList', res);
        const items: OptionItem[] = res.map((item, index) => ({
          value: index,
          label: item,
        }));
        setModelList(items);
      })
      .catch((error) => {
        console.log('getChatModelList error', error);
        setModelList([]);
      })
      .finally(() => {});

    return () => {
      controller.abort();
    };
  }

  useEffect(() => {
    // console.log('useEffect', uri, type, apiKey);
    if (!uri || !type) {
      return;
    }
    loadModelList();
    const matchedOption = modelList.find((item) => item.label === chatModel);
    if (matchedOption) {
      setSelectedModel(matchedOption);
    } else {
      // 未找到时保持label更新
      setSelectedModel({
        label: '未设置',
        value: 0,
      });
    }
  }, [uri, type, apiKey, chatModel, customService]);

  const modelTypeChanged = (value: number) => {
    console.log('modelTypeChanged', value);
    setSelectedModel({
      label: modelList[value].label,
      value,
    });
    onChange?.(modelList[value].label);
  };

  return (
    <Combobox
      frameworks={modelList}
      defaultValue={1}
      value={selectedModel.value}
      onChange={modelTypeChanged}
    />
  );
}
